package org.bringer.webapp.pages;

import java.io.IOException;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;

import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.alerts.AlertManager;
import org.apache.tapestry5.alerts.Duration;
import org.apache.tapestry5.alerts.Severity;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.DiscardAfter;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.PageActivationContext;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PageRenderLinkSource;
import org.bringer.model.Annotation;
import org.bringer.service.AccountManager;
import org.bringer.service.AnnotationManager;
import org.bringer.service.exceptions.UserExistsException;
import org.bringer.webapp.components.AnnotationForm;
import org.bringer.webapp.services.SecurityContext;
import org.hibernate.AnnotationException;
import org.slf4j.Logger;

/**
 * Allow adding new users or viewing/updating existing users
 *
 * @author Serge Eby
 * @version $Id: UserEdit.java 5 2008-08-30 09:59:21Z serge.eby $
 */
public class AnnotationEdit {

    @Inject
    private Logger logger;

    @PageActivationContext(passivate = false)
    @Property(write = false)
    private Annotation annotation;

   

    @Inject
    private PageRenderLinkSource pageRenderLinkSource;

    @Inject
    private Messages messages;

    @Inject
    private SecurityContext securityContext;


    @Inject
    private AccountManager accountManager;
    @Inject
    private AnnotationManager annotationManager;
   

    @Inject
    private HttpServletRequest request;

    @Inject
    private AlertManager alertManager;


  

    @InjectPage
    private Accounts accounts;


    @Persist(PersistenceConstants.FLASH)
    @Property
    private Class goBack;

    @Persist
    @Property(write = false)
    private String from;


   

    @Component(id = "edit")
    private AnnotationForm form;

    private boolean delete = false;

    private boolean cancel = false;

    public void setAccount(Annotation annotation) {
        this.annotation = annotation;
    }


    public Object initialize(Annotation annotation, String from) {
        this.annotation = annotation;
        this.from = from;
        

        return this;
    }

    

    Object[] onPassivate() {
        if (annotation != null && annotation.getId() != null) {
            return new Object[]{annotation};
        }
        return new Annotation[]{};
    }

    void setupRender() {
        if (annotation == null) {
        	annotation = new Annotation();          
        	  annotation.setAnnotationDate(Calendar.getInstance());
        }

       

      

      
    }


    // ~ --- Event Handlers

    @Log
    @DiscardAfter
    Object onCanceledFromEdit() {
        //  return pageRenderLinkSource.createPageRenderLink(goBack);
    	return pageRenderLinkSource.createPageRenderLink(Annotations.class);        
    }

   

    void onPrepare() {
        if (annotation == null) {
            annotation= new Annotation();
            annotation.setAnnotationDate(Calendar.getInstance());
        }
    }

    @Log
    @DiscardAfter
    Object onSuccess() throws UserExistsException, IOException {

        // Delete Button Clicked
        if (delete) {
            return onDelete();
        }

        

        Integer originalVersion = annotation.getVersion();

        try {
        	annotation=annotationManager.save(annotation);        	
        
        } catch (AnnotationException e) {
            // TODO
            //form.recordError(form.getEmailField(), "User exits");
            alertManager.alert(Duration.TRANSIENT, Severity.ERROR,
                    messages.format("errors.existing.annotation", annotation.getDescription())
            );           
            return null;
        }

        if (!"list".equalsIgnoreCase(from)) {
            // add success messages
            alertManager.alert(
                    Duration.TRANSIENT,
                    Severity.INFO,
                    messages.format("annotation.saved", annotation.getDescription()));
           
        } else {
            // add success messages
           
                alertManager.alert(Duration.TRANSIENT, Severity.INFO,
                        messages.format("annotation.added", annotation.getDescription()));
               
               
            
        }
        return Annotations.class;
       
    }

    @Log
    Object onDelete() {
        // Save full name before deletion
       // String id = ""+annotation.getId();
        annotationManager.remove(annotation.getId());
        alertManager.alert(Duration.TRANSIENT, Severity.INFO,
                messages.format("annotation.deleted", annotation.getDescription())
        );
        logger.debug("After deletion.. ready to return userList object");
        return Annotations.class;
    }

    public void setFrom(String from) {
        this.from = from;
    }

   
}
